<?php
namespace app\model;

class Ad{
    public static function Main($system,$theme,$config,$fans,$themeid,$myworker){
        global $_P;
        if ($_P['op']=='savembxx'){
            return  Ad::saveMBXX();
        }
    }

    static function getTemplateId($system,$config,$getlist = false){
//    拼团报名	拼团成功通知
//        预约到店提醒
//        活动进度提醒
//
//    发起砍价	砍价成功通知
//        砍价进度通知
//        砍价结果通知
//
//    盲盒报名	助力成功通知
//        预约到店提醒
//        活动进度提醒
//
//    预售报名	新品开售提醒
//        预约商品开售通知
//        预售尾款支付提醒
//
//    补款	预约到店提醒
//        活动进度提醒
//        新品开售提醒
        $ids = array();
        if ($system['noticeopen']==0){
            return ;
        }

        if ($config['maxcountall']>1){
            $result =  array($system['mb_group_success'],$system['mb_group_goshop'],$system['mb_group_progress']);
        }else{
            $result =  array($system['mb_group_goshop'],$system['mb_group_progress']);
        }

        if ($system['ruanjian']==5){
            $result = array($system['mb_bargain_success'],$system['mb_bargain_progress'],$system['mb_bargain_result']);
        }elseif ($system['ispresale']==1){
            if ($config['yukuan'] > 0 && TIMESTAMP > $config['yukuantime']){
                $config['mb_op'] = intval($config['mb_op'])==0?1:intval($config['mb_op']);
                if ($getlist){
                    $result =  array($system['mb_presale_new'],$system['mb_presale_sale'],$system['mb_presale_payment'],$system['mb_group_goshop'],$system['mb_group_progress'],$system['mb_presale_new']);
                }else{
                    $result =  array($system['mb_group_goshop'],$system['mb_group_progress'],$system['mb_presale_new']);
                }

            }else{
                $result =  array($system['mb_presale_new'],$system['mb_presale_sale'],$system['mb_presale_payment']);
            }
        }

        if ($system['is_mystery_boxes'] == 1 || $system['is_mystery_boxes_feichi'] == 1){
            if (empty($result)){
                $result = array($system['mb_help_success'], $system['mb_group_goshop'], $system['mb_group_progress']);
            }else{
                $result[2]=$system['mb_help_success'];
            }
        }

        if (!empty($result)){
            foreach ($result as $index => $item){
                if (!empty($item)){
                    $ids[]=$item;
                }
            }
        }
        if ($getlist){

            return $ids;
        }else{
            $result = [];
            if (strstr($config['mbxx_mode'],"bottom")!==false ){
                $result['bottom']=$ids;
            }
            if (strstr($config['mbxx_mode'],"submit")!==false ){
                $result['submit']=$ids;
            }
            if (strstr($config['mbxx_mode'],"pay")!==false ){
                $result['pay']=$ids;
            }
            return $result ;
        }
    }

    //获取模版名称及订阅数
    static function getMbName($system,$template_id){
        if ($template_id == $system['mb_group_success']){
            $mbinfo=array(
                'name'=>'拼团成功通知',
                'autosend'=>true,
            );
        }elseif ($template_id == $system['mb_group_goshop']){
            $mbinfo=array(
                'name'=>'预约到店提醒',
                'autosend'=>false,
            );
        }elseif ($template_id == $system['mb_group_progress']){
            $mbinfo=array(
                'name'=>'活动进度提醒',
                'autosend'=>false,
            );
        }elseif ($template_id == $system['mb_bargain_success']){
            $mbinfo=array(
                'name'=>'砍价成功通知',
                'autosend'=>true,
            );
        }elseif ($template_id == $system['mb_bargain_progress']){
            $mbinfo=array(
                'name'=>'砍价进度通知',
                'autosend'=>false,
            );
        }elseif ($template_id == $system['mb_bargain_result']){
            $mbinfo=array(
                'name'=>'砍价结果通知',
                'autosend'=>false,
            );
        }elseif ($template_id == $system['mb_help_success']){
            $mbinfo=array(
                'name'=>'助力成功通知',
                'autosend'=>true,
            );
        }elseif ($template_id == $system['mb_presale_new']){
            $mbinfo=array(
                'name'=>'新品开售提醒',
                'autosend'=>false,
            );
        }elseif ($template_id == $system['mb_presale_sale']){
            $mbinfo=array(
                'name'=>'预约商品开售通知',
                'autosend'=>false,
            );
        }elseif ($template_id == $system['mb_presale_payment']){
            $mbinfo=array(
                'name'=>'预售尾款支付提醒',
                'autosend'=>false,
            );
        }
        return $mbinfo;
    }

    //获取模版订阅数
    static function getMbList($system,$config,$themeid){
        $mbids = Ad::getTemplateId($system,$config,true);
        $mblist=[];
        if (!empty($mbids)){
            foreach ($mbids as $index => $item){
                $mbinfo = Ad::getMbName($system,$item);
                if ($mbinfo){
                    $mbinfo['template_id']= $item;
                    $mbinfo['total'] = db_fetchcolumn ( 'SELECT count(id) as cnt FROM ' . tablename ( t_fans )." where themeid=$themeid and info->'$.\"".$item."_total\"' >= 1" );
                    $mbinfo['count'] = db_fetchcolumn ( 'SELECT count(id) as cnt FROM ' . tablename ( t_fans )." where themeid=$themeid and info->'$.\"".$item."_count\"' >= 1" );
                    $mbinfo['used'] = db_fetchcolumn ( 'SELECT count(id) as cnt FROM ' . tablename ( t_fans )." where themeid=$themeid and info->'$.\"".$item."_used\"' >= 1" );
                    $mbinfo['today'] = db_fetchcolumn ( 'SELECT count(id) as cnt FROM ' . tablename ( t_mbxxlog )." where themeid=$themeid and template_id='".$item."' and sendtime>=" .strtotime(date('Y-m-d 00:00:00')));
                    //***
                    $mbinfo['hexiao'] = db_fetchcolumn (
                        'SELECT count(f.id) as cnt FROM ' . tablename ( t_fans )." as f
                     RIGHT JOIN  ".tablename(t_hexiao)." h on f.themeid = h.themeid and f.uid = h.uid 
                     where f.themeid=$themeid and f.info->'$.\"".$item."_total\"' >= 1"
                    );
                    $mblist[] = $mbinfo;
                }
            }
        }
        return $mblist;
    }

    static function saveMBXX(){
        global $_P,$_G;
        if (empty($_P['mbxx'])){
            return array('error'=>0,'data'=>array('msg'=>'没有模版消息'));
        }
        $themeid = intval($_P['themeid']);
        $fans = db_get(t_fans,['uid'=>$_G['member']['uid'],'themeid'=>$themeid]);
        if (empty($_G['member']['uid']) || empty($fans)){
            return array('error'=>0,'data'=>array('msg'=>'用户信息为空'));
        }
        $mbxx = json_decode(urldecode($_P['mbxx']),true);
        $fans_info = json_decode($fans['info'],true);
        if (!empty(($mbxx)) && is_array($mbxx)){
            foreach ($mbxx as $key => $item){
                if ($item=='accept'){
                    $fans_info[$key.'_total']=intval($fans_info[$key.'_total'])+1;
                    $fans_info[$key.'_count']=intval($fans_info[$key.'_count'])+1;
                }
            }
        }
        db_update(t_fans,array('info'=>json_encode($fans_info)),array('id'=>$fans['id']));

        return array('error'=>0,'data'=>array('msg'=>'保存成功','info'=>$fans_info));
    }

    static function usedMBXX($themeid,$data){
        $fans = db_get(t_fans,['openid'=>$data['touser'],'themeid'=>$themeid]);
        if (empty($fans)){
            return array('error'=>1,'msg'=>'用户信息为空');
        }
        $fans_info = json_decode($fans['info'],true);;
        $key = $data['template_id'];
        if (intval($fans_info[$key.'_count'])>=1){
            $fans_info[$key.'_count']=intval($fans_info[$key.'_count'])-1;
            $fans_info[$key.'_used']=intval($fans_info[$key.'_used'])+1;
        }else{
            return array('error'=>1,'data'=>array('msg'=>'没有可用的订阅'));
        }
        db_update(t_fans,array('info'=>json_encode($fans_info)),array('id'=>$fans['id']));
        return array('error'=>0,'msg'=>'保存成功','info'=>$fans_info,'uid'=>$fans['uid']);
    }
    static function get_moments_tips($config,$fans,$themeid,$themyrecord,$from='wxapp',$op='display')
    {
        return array(
            'openad' => $openad,
            'ad_full' => $ad_full,
            'ad_bottom' => $ad_bottom,
            'friendnum' => $friendnum,
            'open_screen' => $open_screen,
            'video_full' => $video_full,
            'ad_mq_bottom' => $ad_mq_bottom,
            'ad_mq_top' => $ad_mq_top,
            'coupon_info' => $coupon_info,
        );
    }

    /**
     * Desc:获取广告弹窗信息
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/22 8:24 上午
     * @param $config
     * @param $fans
     * @param $themeid
     * @param $themyrecord
     * @return array
     */
    static function get_ad_info($config,$fans,$themeid,$themyrecord,$from='wxapp',$op='display'){
        global $_G,$_P;
        $openad = false;
        $ad_full_list = [];
        $video_open_screen_list = [];
        $video_full_list = [];
        $ad_full = ['status'=>false,'list'=>[]];
        $ad_bottom = ['status'=>false,'list'=>[]];
        $friendnum = ['status'=>false,'list'=>[]];
        $ad_mq_bottom = ['status'=>false,'list'=>[]];//跑马灯首图下
        $ad_mq_top = ['status'=>false,'list'=>[]];//跑马灯首图上
        $open_screen = ['status'=>false,'list'=>[]];
        $video_full= ['status'=>false,'list'=>[]];
        $is_aduser3 = false;
        $is_aduser5 = false;
        $coupon_info = [];


        if ($_P['scene']==1154){
            $ad_bottom = [
                "adimg"=>"http://css2020.yixuan.net/2020css/yx2020/images/moment_bottom.gif",
                "adshow"=>"1",
                "adshownum"=>"999",
                "adsize"=>"100%;bottom:-12rpx;z-index:9999;",
                "adurl"=>"",
                "aduser"=>"0",
                "status"=>true,
            ];
        }

        if (empty($_G['member']['uid']) || $config['is_ad']==false){
            return array(
                'openad' =>$openad,
                'ad_full' =>$ad_full,
                'ad_bottom' =>$ad_bottom,
                'friendnum' =>$friendnum,
                'open_screen' =>$open_screen,
                'video_full' =>$video_full,
                'ad_mq_bottom' =>$ad_mq_bottom,
                'ad_mq_top' =>$ad_mq_top,
                'coupon_info' =>$coupon_info,
            );
        }
        if ($config['ad_style']==1){
            if ($op=='display'){
                $ad_list = Ad::getShowAdList($config,$themeid);
            }else{
                if ($op=='mypay'){
                    $aduser = 12;
                }
                if ($op=='friendhelp'){
                    $aduser = 13;
                }
                $ad_list = Ad::getShowAdList($config,$themeid,$aduser);
            }

        }else{
            $ad_list[0]=array(
                'id'=>1,
                'adimg'=>$config['adimg'],
                'adurl'=>$config['adurl'],
                'adbegintime'=>$config['adbegintime'],
                'adendtime'=>$config['adendtime'],
                'adshow'=>$config['adshow'],
                'adsize'=>$config['adsize'],
                'sort'=>0,
                'themeid'=>$themeid,
            );
        }

        //获取system
        $setting = db_find("SELECT * FROM ".tablename('uni_account_modules')." WHERE module=:module  order by uniacid asc", array(':module' => MODULE_NAME));
        $systems = !empty($setting['settings']) ? xunserializer($setting['settings']) : array();
        $system = $systems;
        if ($system['yx_coupon']){
            require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
            require_once get_path('plugin/coupon/core/model.php');
        }
        
        if (!empty($ad_list)){
            foreach ($ad_list as $key => $val)
            {
                if (!empty($val['adurl']) && $from=='h5'){
                    //h5广告URL解析
                    if ($val['adurl']=='gotorank'){
                        if ($config['rank_show']==3){
                            $val['adurl'] = $_G['siteroot'].createMobileUrl('ranksingle',array("themeid"=>$themeid));
                        }else{
                            $val['adurl'] = '#rank';
                        }
                    }elseif ($val['adurl']=='share'){
                        $val['adurl'] = 'javascript:letgo1();';
                    }elseif (strlen($val['adurl'])<=15){
                        $val['adurl'] = $_G['siteroot'].createMobileUrl($val['adurl'],array("themeid"=>$themeid));
                    }
                }

                //用户范围确认
                $aduser = false;
                if($val['aduser']==0){
                    $aduser = true;
                }elseif($val['aduser']==1 && empty($themyrecord)){
                    $aduser = true;
                }elseif($val['aduser']==2 && !empty($themyrecord)){
                    $aduser = true;
                }elseif($val['aduser']==2 && empty($themyrecord)){
                    //如果免费报名，支付报名等于免费报名成功则显示
                    if (Record::isFreeJoin($config,$themeid) && !empty($fans['username']) && !empty($fans['mobile'])){
                        $gsum12 = (int)db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . " as r
                            WHERE r.themeid ='{$themeid}'  and r.status > 0 and r.status!=3" );
                        if ($gsum12==0){
                            $aduser = true;
                        }
                    }
                }elseif($val['aduser']==3 && $is_aduser3==false && !empty($themyrecord) && $themyrecord['tuannum']>=$val['quantity']){
                    //拼团人数达到
                    $aduser = true;
                    $is_aduser3 = true;
                }
                elseif($val['aduser']==5  && $is_aduser5==false){
                    //推荐成交达到
                    $tuijianzs = (int)db_fetchcolumn("SELECT COUNT(*) FROM " . tablename (t_record) .
                        " WHERE themeid = " . $themeid . " and fromuid = '" . $fans['uid'] ."' and status > 0");
                    if ($tuijianzs>=$val['quantity']){
                        $aduser = true;
                        $is_aduser5 = true;
                    }
                }elseif ($val['aduser']==4){
                    //广告为代理可见
                    $myworker = Worker::getThemeWorkerByUid($fans['uid'],$themeid);
                    if ($myworker['level']==4){
                        $aduser = true;
                    }
                }elseif ($val['aduser']==6 && !empty($themyrecord)){
                    //团长专属
                    if ($themyrecord && $themyrecord['type']==0 && $themyrecord['status']==1){
                        $aduser = true;
                    }
                }elseif ($val['aduser']==7 && !empty($themyrecord)){
                    //支付团员专属
                    if ($themyrecord && $themyrecord['type']==1 && $themyrecord['status']==1){
                        $aduser = true;
                    }
                }elseif ($val['aduser']==8){
                    $themyrecord = db_get(t_record,['themeid'=>$themeid,'uid'=>$fans['uid']]);
                    if ($themyrecord && $themyrecord['status']!=1 || empty($themyrecord)){
                        //未支付团员专属
                        //判断推荐是是否为团长
                        $from_uid = $fans['fromuid'];
                        $from_record = Record::getLastGroupByUid($from_uid,$themeid);
                        if ($from_record  && $from_record['status']==1 && ($from_record['isfinish']!=1 || $config['tuanmode']==1  || $config['tuanmode']==3)){
                            $aduser = true;
                        }
                    }
                }elseif ($val['aduser']==9){
                    //补款
                    $is_bukuan = Record::getBukuanByuid($config,$themeid,$fans['uid']);
                    if ($is_bukuan['isbukuan']==1){
                        $aduser = true;
                    }
                }elseif ($val['aduser']==10){
                    //全款
                    $is_bukuan = Record::getBukuanByuid($config,$themeid,$fans['uid']);
                    if ($is_bukuan['isbukuan']==2){
                        $aduser = true;
                    }
                }elseif ($val['aduser']==11){
                    //全款+补款
                    $is_bukuan = Record::getBukuanByuid($config,$themeid,$fans['uid']);
                    if ($is_bukuan['isbukuan']>0){
                        $aduser = true;
                    }
                }elseif ($val['aduser']==12){
                    //支付凭证页
                    if ($op=='mypay'){
                        $aduser = true;
                    }
                }elseif ($val['aduser']==13){
                    //助力成功
                    if ($op=='friendHelp' || $op=='friendhelp'){
                        $aduser = true;
                    }
                }elseif ($val['aduser']==14){
                    //定金用户
                    $themyrecord = db_get(t_record,['themeid'=>$themeid,'uid'=>$fans['uid'],'status'=>1]);
                    if (TIMESTAMP<$config['yukuantime'] && $themyrecord){
                        $aduser = true;
                    }
                }
//                db_query("ALTER TABLE `yx_yx18900_afans` ADD COLUMN `ad_info` text DEFAULT '' comment '广告点击次数';");
                //判断当前广告是否达到播放上限；
                $adshownum = false;
                if($val['adshow']==0 || $val['adshow']==3 || $val['adshow']==4 || $val['adshow']==5 || $val['adshow']==6
                    || $val['adshow']==1 && !$ad_bottom['status'] || $val['adshow']==2 && !$friendnum['status']){
                    //如果有底部广告或右侧广则不再加载；

                    if ($val['adshownum']==999){
                        $adshownum =true;
                    }else{
                        $fans = Fans::getById($_G['member']['uid'],$themeid);
                        if (!empty($fans['ad_info'])) {
                            $ad_info = unserialize($fans['ad_info']);
                        } else {
                            $ad_info = array();
                        }
                        if ($ad_info[$val['id']]<$val['adshownum']){
                            $adshownum =true;
                            $ad_info[$val['id']] = $ad_info[$val['id']] + 1;
                            $ad_info = serialize($ad_info);
                            $pm = array(":themeid"=>$themeid,":uid"=>$_G['member']['uid']);
                            db_query("UPDATE ".tablename(t_fans)." SET ad_info = '".$ad_info."' WHERE themeid =:themeid and uid = :uid",$pm);
                        }
                    }
                }


                if ($adshownum && $aduser){
                    if ($val['adshow']==0){
                        $ad_full['status'] = $aduser;
                        $tmp_val = $val;
                        $use_btm = false;
                        $tmp_other = json_decode($val['other'],true);
                        $tmp_other['use_btm']=false;
                        if ($tmp_other['ad_btm_img'] && is_array($tmp_other['ad_btm_img'])){
                            $tmp_ad_btm_txt = $tmp_other['ad_btm_txt'];
                            foreach ($tmp_ad_btm_txt as $k1 => $vv1){
                                if (!empty($vv1)){
                                    $tmp_other['ad_btm_txt'][$k1] = $vv1;
                                    $tmp_other['use_btm']=true;
                                    if (empty($tmp_other['ad_btm_img'][$k1])){
                                        $tmp_other['ad_btm_img'][$k1]='https://css2020.yixuan.net/2020css/yx2020/images/ad_btn.png';
                                    }
                                }
                            }

                        }
                        $val['other'] = $tmp_other;
                        $fans = Fans::getById($_G['member']['uid'],$themeid);
                        if ($fans['ad_info']){
                            $ad_info = unserialize($fans['ad_info']);
                            if ($ad_info && is_array($ad_info)){
                                foreach ($ad_info as $Ka =>$va){
                                    if ($val['id']==$Ka && $va<$val['adshownum']){
                                        array_push($ad_full_list,$val);
                                    }
                                    if (!$ad_info[$val['id']]){
                                        array_push($ad_full_list,$val);
                                    }
                                }
                            }
                        }else{
                            //预留判断 991 992 993
//                            $king = '';
//                            $king = 'cbw';
//                            if ($king=='cbw'){
//                                $mode1 = ['url'=>991,'page'=>"/pages/mypay/mypay?softname=" . MODULE_NAME . "&themeid=" . $themeid . "&softkey=" . $theme['softkey'] . "&uid=" . $_G['member']['uid'],'mode'=>1];
//                                $mode2 = ['url'=>992,'function'=>'viewMypay','options'=>0];
//                                $mode3 = ['url'=>993,'page'=>createMobileUrl('mypay',array('themeid'=>$themeid),true),'mode'=>0];
//                                $val['diy_jump']= $mode2;
//                            }
                            array_push($ad_full_list,$val);
                        }

                    }elseif ($val['adshow']==1){
                        //预留判断 991 992 993
//                            $king = '';
//                        $king = 'cbw';
//                        if ($king=='cbw'){
//                            $mode1 = ['url'=>991,'page'=>"/pages/mypay/mypay?softname=" . MODULE_NAME . "&themeid=" . $themeid . "&softkey=" . $theme['softkey'] . "&uid=" . $_G['member']['uid'],'mode'=>1];
//                            $mode2 = ['url'=>992,'function'=>'viewMypay','options'=>0];
//                            $mode3 = ['url'=>993,'page'=>createMobileUrl('mypay',array('themeid'=>$themeid),true),'mode'=>0];
//                            $val['diy_jump']= $mode2;
//                        }
                        $ad_bottom = $val;
                        $ad_bottom['status'] = $aduser;
                    }elseif ($val['adshow']==2){
                        //预留判断 991 992 993
//                            $king = '';
//                        $king = 'cbw';
//                        if ($king=='cbw'){
//                            $mode1 = ['url'=>991,'page'=>"/pages/mypay/mypay?softname=" . MODULE_NAME . "&themeid=" . $themeid . "&softkey=" . $theme['softkey'] . "&uid=" . $_G['member']['uid'],'mode'=>1];
//                            $mode2 = ['url'=>992,'function'=>'viewMypay','options'=>0];
//                            $mode3 = ['url'=>993,'page'=>createMobileUrl('mypay',array('themeid'=>$themeid),true),'mode'=>0];
//                            $val['diy_jump']= $mode2;
//                        }
                        $friendnum = $val;
                        $friendnum['status'] = $aduser;
                    }elseif ($val['adshow']==3){
                        $open_screen['status'] = $aduser;
                        array_push($video_open_screen_list,$val);
                    }elseif ($val['adshow']==4){
                        $video_full['status'] = $aduser;
                        array_push($video_full_list,$val);
                    }elseif ($val['adshow']==5){
                        $tmp_val = $val;
                        $tmp_other = json_decode($val['other'],true);
                        $tmp_other['ad_mq_icon'] = urldecode($tmp_other['ad_mq_icon']);
                        $tmp_val['other'] = $tmp_other;
                        $ad_mq_bottom = $tmp_val;
                        $ad_mq_bottom['status'] = $aduser;
                    }elseif ($val['adshow']==6){
                        $tmp_val = $val;
                        $tmp_other = json_decode($val['other'],true);
                        $tmp_other['ad_mq_icon'] = urldecode($tmp_other['ad_mq_icon']);
                        $tmp_val['other'] = $tmp_other;
                        $ad_mq_top = $tmp_val;
                        $ad_mq_top['status'] = $aduser;
                    }
                }
            }
        }
        if ($ad_full['status'] || $ad_bottom['status'] || $friendnum['status'] || $video_full['status']){
            $openad = true;
        }
//        $ad_full['list']=$ad_full_list;
        $ad_full['list']=$ad_full_list;
        if (count($ad_full_list)>0){
            $ad_full['list']['legnth']=count($ad_full_list);
            $ad_full['list']['length']=count($ad_full_list);
        }

        $open_screen['list']=$video_open_screen_list;
        $video_full['list']=$video_full_list;



        //返回优惠券信息
        //dump($result);
        //判断用户是否存在优惠券
        if ($system['yx_coupon']){
            // $op   其他仅显示未使用   mypay 只显示当前订单已使用的
            if ($op=='mypay'){
                $order_id = $themyrecord['id'];
                $user_used_coupon_total = \CouponModel::userCouponFlagTotal($themeid,$fans['uid'],2,$order_id);
                if ($user_used_coupon_total){
                    $user_coupon_info = \CouponModel::getUserUsedCouponAmountTotal($order_id,$themeid,$fans['uid']);
                    if ($user_coupon_info){
                        $coupon_info['diy_jump']= [];
                        $coupon_info['coupon_img_url'] = $config['coupon_right_icon_bg'];
                        $coupon_info['end_time'] = '';

                        $coupon_info['coupon_money'] = $user_coupon_info;
                        $coupon_info['coupon_money_color'] = $config['coupon_right_txt_color'];
                        $coupon_info['coupon_money_left'] = $config['coupon_right_txt_left'];
                        $coupon_info['coupon_money_top'] = $config['coupon_right_txt_top'];
                        $coupon_info['coupon_money_size'] = $config['coupon_right_txt_size'];
                        $coupon_info['end_tips'] = '已使用';
                        $coupon_info['yx_alert'] = true; //是否显示优惠券列表
                    }
                }
            }else{
                $user_coupon_total = \CouponModel::userCouponFlagTotal($themeid,$fans['uid']);
                if ($user_coupon_total>0){
                    $mode_new = ['url'=>992,'function'=>'openYxAlertShow','options'=>0];
                    $user_coupon_info = \CouponModel::userCouponCanUseInfo($themeid,$fans['uid'],$config);
                    if (($user_coupon_info['end_time'] ||$user_coupon_info['end_tips']) && $user_coupon_info['coupon_money']){
                        $coupon_info['diy_jump']= $mode_new;
                        $coupon_info['coupon_img_url'] = $config['coupon_right_icon_bg'];
                        $coupon_info['end_time'] = $user_coupon_info['end_time'];
                        $coupon_info['coupon_money'] = $user_coupon_info['coupon_money'];
                        $coupon_info['coupon_money_color'] = $config['coupon_right_txt_color'];
                        $coupon_info['coupon_money_left'] = $config['coupon_right_txt_left'];
                        $coupon_info['coupon_money_top'] = $config['coupon_right_txt_top'];
                        $coupon_info['coupon_money_size'] = $config['coupon_right_txt_size'];
                        $coupon_info['end_tips'] = $user_coupon_info['end_tips'];
                        $coupon_info['yx_alert'] = true; //是否显示优惠券列表
                    }
                }

            }

        }
//        $mode1 = ['url'=>991,'page'=>"/pages/mypay/mypay?softname=" . MODULE_NAME . "&themeid=" . $themeid . "&softkey=" . $theme['softkey'] . "&uid=" . $_G['member']['uid'],'mode'=>1];
//        $mode2 = ['url'=>992,'function'=>'viewMypay','options'=>0];
//        $mode3 = ['url'=>993,'page'=>createMobileUrl('mypay',array('themeid'=>$themeid),true),'mode'=>0];
//        $coupon_info['diy_jump']= $mode2;
//        $coupon_info['adurl']= '';
//        $coupon_info['coupon_img_url'] = 'http://img2020.yixuansoft.cn/images/2/2022/11/XkvriQRiIFPARfiRR2KUzfIf8AFuAt.png';
//        $coupon_info['end_time'] = '2022-11-07 17:27:00';
//        $coupon_info['coupon_money'] = 50;
//        $coupon_info['coupon_money_color'] = '#000';
//        $coupon_info['coupon_money_left'] = 30;
//        $coupon_info['coupon_money_top'] = 20;
//        $coupon_info['coupon_money_size'] = 30;
//        $coupon_info['end_tips'] = '已过期';
//        $coupon_info['yx_alert'] = true; //是否显示优惠券列表
        $commssum = Comm::getcommssum([],$themeid,$config['iscommshowfail']);
        if ($config['iscommpop']==3 && $commssum>0 || $config['iscommpop']==4 ){
            $mode1 = ['url'=>991,'page'=>"/packageA/pages/get_red_package/get_red_package",'mode'=>1];
            $coupon_info['diy_jump']= $mode1;
            $coupon_info['adurl']= '';
            if ($config['iscommshowfail']==1){
                $coupon_info['coupon_img_url'] = 'https://css2020.yixuan.net/2020css/yx2020/images/redbag_ti.png';
            }else{
                $coupon_info['coupon_img_url'] = 'https://css2020.yixuan.net/2020css/yx2020/images/redbag_dao.png';
            }
            $coupon_info['end_time'] = '';
            $coupon_info['coupon_money'] = sprintf("%.2f",$commssum==0?'0.00':$commssum);
            $coupon_info['coupon_money_color'] = '#f8394a';
            $coupon_info['coupon_money_size'] = 18;
            $coupon_info['coupon_money_top'] = 16;
            if ($coupon_info['coupon_money']<10){
                $coupon_info['coupon_money_left'] = 23;
            }elseif ($coupon_info['coupon_money']<100){
                $coupon_info['coupon_money_size'] = 17;
                $coupon_info['coupon_money_left'] = 15;
                $coupon_info['coupon_money_top'] = 16;
            }elseif ($coupon_info['coupon_money']<1000){
                $coupon_info['coupon_money'] = intval($coupon_info['coupon_money']);
                $coupon_info['coupon_money_left'] = 23;
            }else{
                $coupon_info['coupon_money'] = intval($coupon_info['coupon_money']);
                $coupon_info['coupon_money_left'] = 17;
            }
            $coupon_info['end_tips'] = '';
            $coupon_info['yx_alert'] = true; //是否显示优惠券列表
        }
        return array(
            'openad' =>$openad,
            'ad_full' =>$ad_full,
            'ad_bottom' =>$ad_bottom,
            'friendnum' =>$friendnum,
            'open_screen' =>$open_screen,
            'video_full' =>$video_full,
            'ad_mq_bottom' =>$ad_mq_bottom,
            'ad_mq_top' =>$ad_mq_top,
            'coupon_info' =>$coupon_info,
        );

    }

    /**
     * Desc:获取弹屏广告并且开启底部按钮的数量
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/11/3 16:52
     * @param $themeid
     * @return int
     */
    static function getBtmBtnListTotal($themeid)
    {
        $total = 0;
        //获取弹窗广告
        $list = db_getall(t_ad,['adshow'=>0,'themeid'=>$themeid]);
        if ($list){
            foreach ($list as $K =>$v){
                $other = json_decode($v['other'],true);
                if ($other['ad_btm_img'] && is_array($other['ad_btm_img']))
                {
                    $total +=1;
                }
            }
        }
        return $total;
    }

    /**
     * Desc:获取用户广告点击类型以及次数
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/11/3 17:26
     * @param $themeid
     * @return array[]
     */
    static function getBtmClickType($themeid)
    {
        $first_arr = ['type'=>2,'title'=>'全部','total'=>0];
        $type_arr = [

            ['type'=>0,'title'=>'取消动作','total'=>0],
            ['type'=>1,'title'=>'确认动作','total'=>0],
        ];
        foreach ($type_arr as $K => $v){
            if ($v['status']!=2){
                $sql = " select count(*) as cnt from ".tablename(t_btm_click_flag)." where themeid=$themeid and type='".$v['type']."'";
                $item_total = db_find($sql)['cnt'];
                $type_arr[$K]['total'] = $item_total;
                $first_arr['total'] += $item_total;
            }
        }
        array_unshift($type_arr,$first_arr);
        return $type_arr;
    }

    /**
     * Desc:出现用户类型
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/11/4 19:24
     * @param $themeid
     * @return int
     */
    static function getBtnClickAdUser($themeid)
    {
        $all_arr = ['aduser'=>999,'title'=>'全部','total'=>0];
        $aduser_arr = [
            ['aduser'=>0,'title'=>'所有用户出现','total'=>0],
            ['aduser'=>1,'title'=>'未付款用户出现','total'=>0],
            ['aduser'=>2,'title'=>'已付款用户出现','total'=>0],
            ['aduser'=>3,'title'=>'拼团人数到达','total'=>0],
            ['aduser'=>5,'title'=>'推荐成交达到','total'=>0],
            ['aduser'=>6,'title'=>'团长','total'=>0],
            ['aduser'=>7,'title'=>'已支付团员','total'=>0],
//            ['aduser'=>8,'title'=>'未支付团员','total'=>0],
            ['aduser'=>9,'title'=>'补款用户','total'=>0],
            ['aduser'=>10,'title'=>'全款用户','total'=>0],
            ['aduser'=>11,'title'=>'补款+全款用户','total'=>0],
        ];
        $all_total=0;
        foreach ($aduser_arr as $k => $v){
            $res = db_getall(t_ad,['themeid'=>$themeid,'aduser'=>$v['aduser'],'adshow'=>0]);
            $ids= '';
            foreach ($res as $kk =>$vv){
                $ids .= $vv['id'].',';
            }
            if ($ids){
                $ids =rtrim($ids,',');
                $sql= " select count(*) as cnt from ".tablename(t_btm_click_flag)." where themeid=$themeid and ad_id in (".$ids.")";
                $total = db_find($sql)['cnt'];
                if ($total>0){
                    $aduser_arr[$k]['total'] = $total;
                    $all_total += $total;
                }
            }
        }
        $all_arr['total'] = $all_total;
        array_unshift($aduser_arr,$all_arr);
        return $aduser_arr;
    }


    static function getBtmClickData($themeid,$type=2,$aduser=999,$search='',$page_start = 0, $page_size = 10,$start_day, $end_day,$count=0)
    {
        $condition = '';
        if ($search){
            $condition .= " AND (b.nickname LIKE '" . $search . "'" . " or b.mobile LIKE '" . $search . "' " . " or b.username LIKE '" .  $search . "') ";
        }
        if ($start_day && $end_day) {
            $condition .= "  and a.created_at between '" . $start_day . "' and '" . $end_day . "'";
        }
        if ($type!=2){
            $condition .= " and a.type='$type'";
        }
        if ($aduser!=999){
            $condition .= " and f.aduser='$aduser'";
        }
        $condition .= " order by a.created_at desc ";
        if ($page_size && !$count){
            $condition .= "LIMIT " . $page_start . "," . $page_size;
        }
        $sql = " from ".tablename(t_btm_click_flag)." as a ".
        " left join ".tablename(t_fans)." as b on a.uid=b.uid and a.themeid=b.themeid".
        " left join ".tablename(t_worker)." as c on a.workerid=c.uid and a.themeid=c.themeid".
        " left join ".tablename(t_ad)." as d on d.id=a.ad_id and a.themeid=d.themeid".
        " left join ".tablename(t_fans)." as e on e.uid=a.from_uid and a.themeid=e.themeid".
        " left join ".tablename(t_ad)." as f on f.id=a.ad_id and a.themeid=e.themeid".
        " where a.themeid=$themeid".$condition;
        if ($count){
            return intval(db_fetchcolumn(' select count(*)'.$sql));
        }else{
            $sql = " select a.*,b.nickname,b.avatar,b.username,b.mobile,c.username as workername,c.avatar as worker_avatar,e.avatar as from_avatar,e.username as from_username".$sql;
            $list = db_select($sql);
            foreach ($list as $K=> $v){
                $user_record= Record::getLastGroupByUid($v['uid'],$themeid);
                if ($user_record && $user_record['status']==1){
                    $list[$K]['has_order'] =true;
                }else{
                    $list[$K]['has_order'] =false;
                }
            }
            return $list;
        }
    }

    /**
     * Desc:用户插入广告点击记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/11/1 17:00
     * @param $system
     * @param $config
     * @param $themeid
     * @param $fans
     */
    static function fansSubInfo($system,$config,$themeid,$fans,$from_uid=0)
    {
        global $_G,$_P;
        $op = $_P['op'];
        $ad_id = $_P['ad_id'];
        $from_uid = $_P['fromuid'];
        $workerid = $_P['workerid'];
        if ($op=='undefined'){
            $op =0;
        }
        $insert_data = [
            'uid'=>$fans['uid'],
            'from_uid'=>$from_uid,
            'workerid'=>$workerid,
            'ad_id'=>$ad_id,
            'type'=>$op,
            'themeid'=>$themeid
        ];
        if ($system['yx_coupon']!=1){
            $res = $insertid = db_insert(t_btm_click_flag,$insert_data);
        }
        if ($op==''){
            $op=0;
        }
        //判断广告是否绑定优惠券
        $ad_item = Ad::getOne($ad_id,$themeid);
        //判断按钮是否绑定 优惠券
        if ($system['yx_coupon']==1 && $ad_item){
            require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
            require_once get_path('plugin/coupon/core/model.php');
            $ad_other = json_decode($ad_item['other'],true);
            $ad_btm_coupon_id_arr = $ad_other['ad_btm_coupon_id'];
            try {
                if ($ad_btm_coupon_id_arr[$op]){
                    //补丁 修复op为空
                    $insert_data['type'] = 1;
                    $res = $insertid = db_insert(t_btm_click_flag,$insert_data);
                    //按钮绑定优惠券 则为确认
                    $fanstemp = Fans::getworkerid_fromuid($themeid,$fans);
                    $themyrecord = db_get(t_record,['themeid'=>$themeid,'uid'=>$fans['uid']]);
                    //插入用户优惠券
                    $tmp_coupon_id= $ad_btm_coupon_id_arr[$op];
                    \CouponModel::userCouponAutoGet($themeid,$fanstemp['workerid'],$themyrecord,$fans['uid'],$tmp_coupon_id);

                    $fans = Fans::getById($_G['member']['uid'],$themeid);
                    if (!empty($fans['ad_info'])) {
                        $ad_info = unserialize($fans['ad_info']);
                    } else {
                        $ad_info = array();
                    }
                    $ad_info[$ad_id] = 1000;
                    $ad_info = serialize($ad_info);
                    $pm = array(":themeid"=>$themeid,":uid"=>$_G['member']['uid']);

                    db_query("UPDATE ".tablename(t_fans)." SET ad_info = '".$ad_info."' WHERE themeid =:themeid and uid = :uid",$pm);
                    return ['get_coupon'=>true];
                }else{
                    //补丁 修复op为空
                    $insert_data['type'] = 0;
                    $res = $insertid = db_insert(t_btm_click_flag,$insert_data);
                }
            }catch (Exception $e){
                var_dump($e->getMessage());die();
            }
        }else{
            //不开启优惠券
            //如果为确认 执行粉丝中的ad_info 对应的广告id次数更新为0
            if ($op==1 && $res){
                $fans = Fans::getById($_G['member']['uid'],$themeid);
                if (!empty($fans['ad_info'])) {
                    $ad_info = unserialize($fans['ad_info']);
                } else {
                    $ad_info = array();
                }
                if ($ad_info[$ad_id]){
                    $ad_info[$ad_id] = 1000;
                    $ad_info = serialize($ad_info);
                    $pm = array(":themeid"=>$themeid,":uid"=>$_G['member']['uid']);
                    db_query("UPDATE ".tablename(t_fans)." SET ad_info = '".$ad_info."' WHERE themeid =:themeid and uid = :uid",$pm);
                }
            }
        }
        return ['get_coupon'=>false];
    }

    //获取团队提示
    static function get_tuan_tips($config,$themeid,$themyrecord)
    {
        global $_G;
        $result = array('success'=>[],'next'=>[]);
        if (empty($_G['member']['uid']) || empty($themyrecord) || $config['maxcountall']<=1 || empty($config['tuan_tips'])){
            return $result;
        }

        //获取组团成功信息
        if ($themyrecord['tuannum']>1){
            $tuan_tips = array_reverse($config['tuan_tips']);
            foreach ($tuan_tips as $index=>$item){
                if ($themyrecord['tuannum']>=$item['num']){

                    $fans = Fans::getById($_G['member']['uid'],$themeid);
                    if (!empty($fans['other_info'])) {
                        $fans_info = unserialize($fans['other_info']);
                    } else {
                        $fans_info = array();
                    }
                    if ($fans_info['tuan_tips'.$item['num']]!=true){
                        $result['success']=$item;
                        $result['success']['share']='开心收下';
                        $result['success']['tips']= $item['num'].'人组队成功';
                        $result['success']['name']= '获得'.$item['name'];
                        //更新状态只提醒一次
                        $fans_info['tuan_tips'.$item['num']]=true;
                        $pm = array(":themeid"=>$themeid,":uid"=>$_G['member']['uid']);
                        db_query("UPDATE ".tablename(t_fans)." SET other_info = '".serialize($fans_info)."' WHERE themeid =:themeid and uid = :uid",$pm);
                    }
                    break;
                }
            }
        }

        //获取组团成功信息
        $tuan_tips = $config['tuan_tips'];
        foreach ($tuan_tips as $index=>$item){
            if ($themyrecord['tuannum']<$item['num']){
                $result['next']=$item;
                $result['next']['share']='立即邀请';
                $cha = $item['num']-$themyrecord['tuannum'];
                $result['next']['tips']='您再邀请'.$cha.'人报名，即完成'.$item['num'].'人组队';
                $result['next']['name']= '将获得'.$item['name'];
                break;
            }
        }
        return $result;
    }

    /**
     * Desc:获取弹屏广告列表
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/20 8:30 上午
     * @param $themeid
     * @return mixed
     */
    public static function getAdList($themeid)
    {
        $sql = " select * from ".tablename(t_ad)." where themeid=$themeid order by adbegintime";
        return db_select($sql);
    }

    /**
     * Desc:增加弹屏广告
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/20 8:38 上午
     * @param int $ad_id
     * @param $data
     * @return mixed
     */
    public static function insertAdItem($data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s");
        $res = $insertid = db_insert(t_ad,$data);
        return $res;
    }

    /**
     * Desc:修改弹屏广告
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/20 8:55 上午
     * @param $where
     * @param $data
     * @return bool
     */
    public static function editItemByWhere($where,$data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s");
        $res = db_update(t_ad,$data,$where);
        if (!empty($res)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Desc:获取广告item
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/20 9:38 上午
     * @param $id
     * @param $themeid
     * @return mixed
     */
    public static function getOne($id,$themeid)
    {
        $res = db_get(t_ad,['id'=>$id,'themeid'=>$themeid]);
        return $res;
    }

    /**
     * Desc:删除item
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/20 10:27 上午
     * @param $id
     * @return mixed
     */
    public static function delItem($id)
    {
        return db_delete(t_ad,['id'=>$id]);
    }

    /**
     * Desc:获取可展示的弹窗广告
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/22 9:12 上午
     * @param $themeid
     */
    public static function getShowAdList($config,$themeid,$aduser=-1)
    {
        global $_P;
        $now_time = time();
        if($_P['recordid']==99999){
            $now_time = $config['yukuantime']+600;
        }
        $condition ='';
        if ($aduser!=-1){
            $condition .= " and aduser=$aduser";
        }
        $sql = " select * from ".tablename(t_ad) ." where themeid=$themeid  and adbegintime <=$now_time and adendtime>$now_time ".$condition." order by quantity desc,id asc ";
        $list = db_select($sql);
        return $list;
    }

    /**
     * Desc:判断对应类型过期广告
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/22 11:51 上午
     * @param $themeid
     * @param int $adshow
     * @return mixed
     */
    public static function getOutAdItem($themeid,$adshow=0)
    {
        $now_time = time();
        $sql = " select adimg,adurl,adshow,adsize,adshownum,aduser from ".tablename(t_ad) ." where themeid=$themeid and adshow=$adshow and adimg != '' and adendtime <=$now_time limit 1";
        $list = db_find($sql);
        return $list;
    }

    public static function getSelfInfo($fans,$config,$themeid,$system){
        global $_G,$_P;
        $is_open_boxs = false;
        if (empty($_G['member']['uid'])){
            return ;
        }
        $is_get_box=false;
        $fans = db_get(t_fans,['id'=>$fans['id'],'themeid'=>$themeid]);
        $fans['other_info'] = unserialize($fans['other_info']);
        $formuid_record_pay = Record::getRecordByUid($_G['member']['uid'],$themeid);//是否下单
        if ($config['get_mystery_boxes']==1) {
            $is_get_box = Record::isGroupFinish($_G['member']['uid'], $themeid);
        }elseif (($config['get_mystery_boxes']==2) && $fans['username'] && $fans['click_open_box']){
            $is_get_box = true;
        }elseif (($config['get_mystery_boxes']==3) && !empty($formuid_record_pay)){
            $is_get_box = true;
        }
        if ($config['mystery_is_preview']==1){
            $is_get_box=true;
        }

        if ($config['get_mystery_boxes']==2) {
            $formuid_record = Record::getRecordByUidNopay($_G['member']['uid'],$themeid);
        }else{
            $formuid_record = $formuid_record_pay;
        }

        $is_open_boxs = false;
        if (!empty($formuid_record['address'])){
            $gift = Ad::getFansBoxGiftMult($config, $formuid_record['address']);
            if (!empty($gift)){
                $count = count($gift);
                //如果有拼团成功盲盒，且客户拼团成功则礼品减一
                if ($config['mystery_friend_mode5']==1) {
                    if (Record::isGroupFinish($_G['member']['uid'], $themeid)){
                        $count --;
                    }
                }
                //如果有支付成功盲盒，且客户拼团成功则礼品减一
                if (($config['mystery_friend_mode4']==1) && !empty($formuid_record_pay)){
                    $count --;
                }

                //纯助力模式
                if($config['mystery_friend_need2']>0){
                    if($config['mystery_friend_need3']>0) {
                        if ($count>2){
                            $is_open_boxs = true;
                            $is_finish_friend = true;
                        }
                    }else{
                        if ($count>1){
                            $is_open_boxs = true;
                            $is_finish_friend = true;
                        }
                    }
                }elseif ($count>0){
                    $is_open_boxs = true;
                    $is_finish_friend = true;
                }
            }
        }
        if (empty($formuid_record['address']) || $is_open_boxs == false){
            if ($is_get_box){
                $count = count($gift);
                if ($count==0){
                    $friend_status_tips = '获得一个盲盒！';
                }elseif ($count==1){
                    $friend_status_tips = '获得两个盲盒！';
                }elseif ($count==2){
                    $friend_status_tips = '获得三个盲盒！';
                }
                //如果有拼团成功盲盒，且客户拼团成功则礼品减一
                if ($config['mystery_friend_mode5']==1) {
                    if (Record::isGroupFinish($_G['member']['uid'], $themeid)){
                        $count --;
                        if (empty($fans['other_info']['mode5'])){
                            $fans['other_info']['mode5']=1;
                        }
                    }
                }
                //如果有支付成功盲盒，且客户拼团成功则礼品减一
                if (($config['mystery_friend_mode4']==1) && !empty($formuid_record_pay)){
                    $count --;
                    if (empty($fans['other_info']['mode4'])){
                        $fans['other_info']['mode4']=1;
                    }
                }
                //已获得多少个邀请
                if ($count==0){
                    $mystery_friend_need=$config['mystery_friend_need'];
                }elseif ($count==1){
                    $mystery_friend_need=$config['mystery_friend_need']+$config['mystery_friend_need2'];
                }elseif ($count==2){
                    $mystery_friend_need=$config['mystery_friend_need']+$config['mystery_friend_need2']+$config['mystery_friend_need3'];
                }else{
                    $mystery_friend_need=-1;
                }
                $friend_num = $fans['friendnum'];
                if ($friend_num>=$mystery_friend_need || ($config['mystery_mode']==1 && !empty($formuid_record_pay)) || ($config['mystery_mode']==2 && Record::isGroupFinish($_G['member']['uid'], $themeid)) ){
                    //邀请好友助力完成
                    $is_finish_friend = true;
                    if (empty($fans['other_info']['need' . $count])){
                        $fans['other_info']['need' . $count]=1;
                    }
                }else{
                    //未完成
                    $is_finish_friend = false;
                    $need_friend_num = $mystery_friend_need - $friend_num;
                }
            }
        }

        db_update(t_fans,array('other_info'=>serialize($fans['other_info'])),array('id'=>$fans['id']));

        $self = array(
            "avatar"=>$fans['avatar'],
            "username"=>$formuid_record['username'],
            "is_get_box" => $is_get_box ,
            "is_finish_friend" => $is_finish_friend ,
            "is_open_boxs" => $is_open_boxs ,
            "gift" => count($gift)>0?$gift[0]:'' ,
            "gifts" => $gift ,
            "need_friend_num" => $need_friend_num,
        );

        //判断2、3模式下的盲盒进度的展现形式 0大图  1小图
        if ($config['get_mystery_boxes']==2 || $config['get_mystery_boxes']==3){
            if ($config['mystery_process_show']==0 || $friend_num==0){
                $self['mystery_process_show'] = 0;
            }else{
                $self['mystery_process_show'] = 1;
            }
            $self['mystery_process_show_small_img']= $config['mystery_process_show_small_img'];
        }else{
            $self['mystery_process_show'] = 0;
        }
        //如果找开的好友链接，并未帮助力，先助力
//    if (!empty($_P['fromuid'])){
//        $is_friend_help = Record::isFriendHelp($_G['member']['uid'],$_P['fromuid'],$themeid);
//        if (!$is_friend_help){
//            $formuid_fans = Fans::getById($_P['fromuid'],$themeid);
//            if ($formuid_fans['friendnum']<$config['mystery_friend_need']) {
//                $self['mystery_process_show'] = 1;
//            }
//        }
//    }
        $self['need_tips'] = '';
        if ($self['need_friend_num']>0){
            $self['need_tips'] .= '再邀请' . $self['need_friend_num'] .'位好友';
        }

        $self['is_zhifu'] = true;
        $self['is_pingtuan'] = true;

        //如果有支付成功盲盒，且客户拼团成功则礼品减一
        if ($config['mystery_friend_mode4']==1){
            if (empty($formuid_record_pay)){
                if (!empty($self['need_tips'] )){
                    $self['need_tips']  .="或成功支付抢购";
                }else{
                    $self['need_tips'] = '您再成功支付抢购';
                }
                if ($self['is_open_boxs']==false){
                    $self['is_zhifu'] = true;
                }else{
                    $self['is_zhifu'] = false;
                }
                // $self['is_open_boxs'] = false;
            }
        }
        //如果有拼团成功盲盒，且客户拼团成功则礼品减一
        if ($config['mystery_friend_mode5']==1) {
            if (!Record::isGroupFinish($_G['member']['uid'], $themeid)){
                if (!empty($self['need_tips'] )){
                    $self['need_tips']  .="或拼团成功";
                }else{
                    $self['need_tips'] = '您再拼团成功';
                }
                if ($self['is_open_boxs']==false){
                    $self['is_pingtuan'] = true;
                }else{
                    $self['is_pingtuan'] = false;
                }
                // $self['is_open_boxs'] = false;
            }
        }
        $self['mystery_gift_select'] = $config['mystery_gift_select'];
        $self['is_select_gift'] = false;
        if (!empty($config['mystery_gift_select'])){
            $select_gift = strstr($formuid_record['address'],"|选中");
            if ($select_gift!==false){
                $select_gift = str_replace("|选中","",$select_gift);
                $end = strpos($select_gift,"|");
                if ($end>0){
                    $select_gift = substr($select_gift, 0, $end);
                }
                if (!empty($self['gifts'])){
                    foreach ($self['gifts'] as $index => $row) {
                        if ($select_gift==$row['name']){
                            $self['gifts'] = array(
                                0=>$row
                            );
                            $self['mystery_gift_select'] = 0;
                            $self['is_select_gift'] = true;
                            break;
                        }
                    }
                }
            }else{
                if (!empty($config['mystery_friend_mode3'])){
                    $open_num = 3;
                }elseif (!empty($config['mystery_friend_mode2'])){
                    $open_num = 2;
                }else{
                    $open_num = 1;
                }
                if ($open_num <= count($gift)){
                    $self['mystery_gift_select'] = $open_num;
                }
            }
        }

        if ($config['mystery_boxes_endtime_set']==1 && $config['mystery_boxes_endtime']<TIMESTAMP){
            //若时间过期则不再提示盲盒信息
            if (count($self['gifts'])>0){
                $self['is_zhifu'] = true;
                $self['is_pingtuan'] = true;
                $self['need_tips']="";
                $self['is_finish_friend']=true;
                $self['is_open_boxs']=true;
            }else{
                $self=array();
            }
        }
        return $self;
    }
    public static function get_boxes_max_num($config){
        if (!empty($config['mystery_friend_mode3'])){
            $open_num = 3;
        }elseif (!empty($config['mystery_friend_mode2'])){
            $open_num = 2;
        }else{
            $open_num = 1;
        }
        return $open_num;
    }
    public static function getFriendInfo($fromuid,$config,$themeid,$system){
        global $_G;
        $fromuid = intval($fromuid);
        if ($config['mystery_friend_mode1'] >0){
            //若为支付或拼团成功即可拆，等于无裂变，好友不弹框；
            return ;
        }
        if ($config['mystery_boxes_endtime_set']==1 && $config['mystery_boxes_endtime']<TIMESTAMP){
            //若时间过期则不再提示盲盒信息
            return ;
        }
        if (empty($fromuid)){
            return;
        }

        $is_get_box=false;
        $need_friend_info = false;
        $formuid_fans = Fans::getById($fromuid,$themeid);
        $formuid_record_pay = Record::getRecordByUid($fromuid,$themeid);
        $isworker = Worker::getThemeWorkerByUid($fromuid,$themeid,1);
        if (empty($isworker)){
            if ($config['get_mystery_boxes']==1) {
                $is_get_box = Record::isGroupFinish($fromuid, $themeid);
            }elseif (($config['get_mystery_boxes']==2) && $formuid_fans['username'] && $formuid_fans['click_open_box'] || !empty($formuid_record_pay)){
                $is_get_box = true;
            }elseif (($config['get_mystery_boxes']==3) && !empty($formuid_record_pay)){
                $is_get_box = true;
            }
        }

        //判断当前是否可以帮助拆盲盒
        $can_help_friend = true;
        if ($config['mystery_friend_help']>0 && !empty($_G['member']['uid'])){
            $select_sql = " SELECT COUNT(*) AS cnt FROM ".tablename(t_friend)." WHERE themeid=$themeid AND uid = '{$_G['member']['uid']}' AND status=1";
            $used_help_friend_num =  db_find($select_sql)['cnt'];
            if ($used_help_friend_num>=$config['mystery_friend_help']){
                $can_help_friend = false;
            }
        }
        //收集好友客资 判断
        if ($config['mystery_get_friend_info']==0){
            $need_friend_info = 0;
        }else{
            $uid_fans = Fans::getById($_G['member']['uid'],$themeid);
            if ($config['mystery_get_friend_info']==1){
                if (!empty($uid_fans['username'])){
                    $need_friend_info = 0;
                }else{
                    $need_friend_info = 1;
                }
            }elseif ($config['mystery_get_friend_info']==2){
                if (!empty($uid_fans['mobile'])){
                    $need_friend_info = 0;
                }else{
                    $need_friend_info = 2;
                }
            }
        }

        if ($config['get_mystery_boxes']==2) {
            $formuid_record = Record::getRecordByUidNopay($fromuid,$themeid);
        }else{
            $formuid_record = $formuid_record_pay;
        }

        $is_open_boxs = false;
        if (!empty($formuid_record['address'])){
            $gift = Ad::getFansBoxGiftMult($config, $formuid_record['address']);
            if (!empty($gift)){
                $count = count($gift);
                //如果有拼团成功盲盒，且客户拼团成功则礼品减一
                if ($config['mystery_friend_mode5']==1) {
                    if (Record::isGroupFinish($fromuid, $themeid)){
                        $count --;
                    }
                }
                //如果有支付成功盲盒，且客户拼团成功则礼品减一
                if (($config['mystery_friend_mode4']==1) && !empty($formuid_record_pay)){
                    $count --;
                }

                //纯助力模式
                if($config['mystery_friend_need2']>0){
                    if($config['mystery_friend_need3']>0) {
                        if ($count>2){
                            $is_open_boxs = true;
                            $is_finish_friend = true;
                        }
                    }else{
                        if ($count>1){
                            $is_open_boxs = true;
                            $is_finish_friend = true;
                        }
                    }
                }elseif ($count>0){
                    $is_open_boxs = true;
                    $is_finish_friend = true;
                }
            }
        }
        if (empty($formuid_record['address']) || $is_open_boxs == false){
            //是否拼团成功
            if ($is_get_box){
                $count = count($gift);
                if ($count==0){
                    $friend_status_tips = '获得一个盲盒！';
                }elseif ($count==1){
                    $friend_status_tips = '获得两个盲盒！';
                }elseif ($count==2){
                    $friend_status_tips = '获得三个盲盒！';
                }
                //如果有拼团成功盲盒，且客户拼团成功则礼品减一
                if ($config['mystery_friend_mode5']==1) {
                    if (Record::isGroupFinish($fromuid, $themeid)){
                        $count --;
                    }
                }

                //如果有支付成功盲盒，且客户拼团成功则礼品减一
                if (($config['mystery_friend_mode4']==1) && !empty($formuid_record_pay)){
                    $count --;
                }
                //已获得多少个邀请
                if ($count==0){
                    $mystery_friend_need=$config['mystery_friend_need'];
                }elseif ($count==1){
                    $mystery_friend_need=$config['mystery_friend_need']+$config['mystery_friend_need2'];
                }elseif ($count==2){
                    $mystery_friend_need=$config['mystery_friend_need']+$config['mystery_friend_need2']+$config['mystery_friend_need3'];
                }else{
                    $mystery_friend_need=-1;
                }

                $friend_num = $formuid_fans['friendnum'];

                if ($friend_num>=$mystery_friend_need || ($config['mystery_mode']==1 && !empty($formuid_record_pay)) || ($config['mystery_mode']==2 && Record::isGroupFinish($fromuid, $themeid)) ){
                    //邀请好友助力完成
                    $is_finish_friend = true;
                }else{
                    $is_finish_friend = false;
                }
                $is_friend_help = Record::isFriendHelp($_G['member']['uid'],$fromuid,$themeid);
                if (!$is_finish_friend){
                    $need_friend_num = $mystery_friend_need - $friend_num;
                    $need_friend_num = max(0,$need_friend_num);
                }else{
                    $need_friend_num = 0;
                }
                if($config['get_mystery_boxes']==2){
                    $self_record = Record::getRecordByUidNopay($_G['member']['uid'],$themeid);
                }else{
                    $self_record = Record::getRecordByUid($_G['member']['uid'],$themeid);
                }

                if (!empty($self_record)){
                    $is_reg = true;
                }else{
                    $is_reg = false;
                }
            }
        }

        $friend = array(
            "fromuid"=>$formuid_fans['uid'],
            "avatar"=>$formuid_fans['avatar'],
            "username"=>$formuid_record['username']?$formuid_record['username']:$formuid_fans['username'],
            "is_get_box" => $is_get_box ,
            "is_finish_friend" => $is_finish_friend ,
            "friend_status_tips" => $friend_status_tips,
            "is_open_boxs" => $is_open_boxs ,
            "gift" => $gift ,
            "is_friend_help" => $is_friend_help ,
            "is_reg" => $is_reg ,
            "need_friend_num" => $need_friend_num ,
            "need_friend_info" => $need_friend_info ,
            "can_help_friend" => $can_help_friend ,
        );
        return $friend;
    }
//    获取地址选项的中奖，show读取所有项目，get按中奖率获取其中一个
    public static function getAddressGift($themeid,$status = 'show'){
        global $_G;
        $config = Theme::getConfig($themeid);
        if (empty($config['addressoptions'])){
            return array();
        }
        $arr = array();
        $yizhong = array();
        $open_num = Ad::get_boxes_max_num($config);
        //新增库存字段，若库存全部未设置，则重置为10000；
//        $addressstock = 0;
//        foreach ($config['addressoptions'] as $index=>$value) {
//            $addressstock += $config['addressstock'][$index];
//        }
//        if ($addressstock==0){
//            foreach ($config['addressoptions'] as $index=>$value) {
//                $config['addressstock'][$index]=10000;
//                $config['address_status'][$index]=0;
//            }
//        }

        //当前用户获得的奖品
        if ($config['get_mystery_boxes']==2){
            $formuid_record = Record::getRecordByUidNopay($_G['member']['uid'],$themeid);
        }else{
            $formuid_record = Record::getRecordByUid($_G['member']['uid'],$themeid);
        }
        if (!empty($formuid_record['address'])){
            $giftname = explode('|',$formuid_record['address']);
            if ($config['mystery_gift_get']==0){
                $giftname = array_flip($giftname);
                $giftname = array_flip($giftname);
            }
            // if ($status == 'show'){
                foreach ($giftname as $index=>$value) {
                    $index = array_search($value,$config['addressoptions']);

                    if ($index!==false){
                        $data=array(
                            'yizhong'=>true,
                            'price'=>$config['addressprice'][$index],
                            'img'=>$config['addressimg'][$index],
                            'name'=>$config['addressoptions'][$index],
                            'linkimg'=>$config['addresslinkimg'][$index],
                            'showname'=>$config['addressoptions_show'][$index],
                        );
                        if (count($yizhong)<$open_num){
                            array_push($yizhong, $data);
                        }
                    }
                }
            // }

        }else{
            $giftname=array();
        }

        $yizhong_shu = count($yizhong)+1;
        //如果已中数大于配置数，直接返回空值
        if ($status == 'get' && $yizhong_shu>$open_num){
            return array();
        }
        $probability = 0;
        foreach ($config['addressoptions'] as $index=>$value) {
            if (!empty($value) && $config['address_status'][$index]==0 && (($config['addressprobability'][$index]>1 && $config['addressstock'][$index]>0) && ($config['address_type'][$index]==0 || $config['address_type'][$index]==$yizhong_shu) || $status == 'show')){
                $data=array(
                    'price'=>$config['addressprice'][$index],
                    'img'=>$config['addressimg'][$index],
                    'name'=>$config['addressoptions'][$index],
                    'linkimg'=>$config['addresslinkimg'][$index],
                    'showname'=>$config['addressoptions_show'][$index],
                );
                if ($status == 'get'){
                    $probability += $config['addressprobability'][$index];
                    $data['probability'] = $config['addressprobability'][$index];
                    $data['index'] = $index;
                }
                if ($config['mystery_gift_get']==1 || !in_array($data['name'],$giftname)) {
                    $data['yizhong']=false;
                    array_push($arr, $data);
                }
            }
        }

        if ($status == 'get'){
            if ($probability==0 ){
                return array();
            }
            $arr = Ad::arraySort($arr,'probability');
            $beishu = 100/$probability;
            $rand = rand(0,10000)/100;
            $now = 0;
            foreach ($arr as $index=>$value) {
                $now =$now + ($value['probability']*$beishu);
                if ($rand<$now || $index==count($arr)-1){
                    $result = $value;
                    break;
                }
            }
            $config_save = 	Theme::getConfig($themeid,true);
            $config_save['addressstock'][$result['index']]=$config_save['addressstock'][$result['index']]-1;
            Theme::setConfig($config_save,$themeid,$_G['mpid']);
        }else{
            $result = array_merge( $yizhong,$arr);
        }
        return $result;
    }
    public static function getFansBoxGift($config,$giftname){$arr = array();
        if (empty($config['addressoptions'])){
            return array();
        }
        foreach ($config['addressoptions'] as $index=>$value) {
            if ($value==$giftname){
                $data=array(
                    'price'=>$config['addressprice'][$index],
                    'img'=>$config['addressimg'][$index],
                    'name'=>$config['addressoptions'][$index],
                    'linkimg'=>$config['addresslinkimg'][$index]
                );
                break;
            }
        }
        return $data;
    }
    public static function getFansBoxGiftMult($config,$giftname)
    {
        $arr = array();
        if (empty($config['addressoptions']) || empty($giftname)) {
            return array();
        }
        $giftname = explode('|', $giftname);
        if ($config['mystery_gift_get']==0){
            $giftname = array_flip($giftname);
            $giftname = array_flip($giftname);
        }
        $open_num = Ad::get_boxes_max_num($config);
        $data = array();
        foreach ($giftname as $index=>$value) {
            $index = array_search($value,$config['addressoptions']);
            if ($index!==false){
                if (count($data)<$open_num){
                    $data[]=array(
                        'price'=>$config['addressprice'][$index],
                        'img'=>$config['addressimg'][$index],
                        'name'=>$config['addressoptions'][$index],
                        'linkimg'=>$config['addresslinkimg'][$index],
                        'showname'=>$config['addressoptions_show'][$index]
                    );
                }
            }
        }
        return $data;
    }

    public static function arraySort($array,$keys,$sort='asc') {
        $newArr = $valArr = array();
        foreach ($array as $key=>$value) {
            $valArr[$key] = $value[$keys];
        }
        ($sort == 'asc') ?  asort($valArr) : arsort($valArr);
        reset($valArr);
        $index = 0 ;
        foreach($valArr as $key=>$value) {
            $newArr[$index] = $array[$key];
            $index++;
        }
        return $newArr;
    }

    /**
     * Desc:删除广告点击记录
     * Author:cbw
     * Time: 2023/8/11 03:37
     * @param $where
     * @return mixed
     */
    public static function deleteAdBtmClickFlag($where)
    {
        return db_delete(t_btm_click_flag,$where);
    }
}